package 链表;

import common.ListNode;

/**
 * @author tmh
 * @date 2024/8/29 22:47
 * @description
 */
public class T19删除链表的倒数第N个结点_2次解 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        //求出链表的长度
        int len = 0;
        ListNode p = head;
        while (p != null) {
            len++;
            p = p.next;
        }
        //定义一个虚拟节点dummy执行head的前面
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        p = dummy;
        //定位到要删除节点的前面一个节点
        for (int i = 0; i < len - n; i++) {
            p = p.next;
        }
        //删除节点
        p.next = p.next.next;
        return dummy.next;
    }
}
